#include "app.h"

#include <stdarg.h>
#include <stdio.h>
#include <string.h>

extern UART_HandleTypeDef huart2;
uint8_t UartIRQFlag;
uint8_t uartRxBuffer[256];
uint8_t app_debug = 0;
uint8_t app_device = 0;

extern DMA_HandleTypeDef hdma_usart2_rx;

int app_set_vdd(uint8_t dev_num, double value)
{
	if (value > 4.5) {
		return 1;
	}

	double R1 = 12000.0 * (value / 0.8 - 1.0);

	uint8_t tap = 256.0 * (1.0 - R1 / 50000.0);

	bsp_max5400(dev_num, tap);

	return 0;
}

int app_vdd_en(uint8_t dev_num, uint8_t state)
{
	bsp_asw(dev_num, state);
	return 0;
}

int app_start(void)
{
	printf("MiniPD-LCD Start, type help for usage\r\n");
	/* Initial Shell */
	do {
		ntshell_init(
		    &ntshell,
		    func_read,
		    func_write,
		    func_callback,
		    (void *)&ntshell);
		ntshell_set_prompt(&ntshell, "#");
	} while (0);

	printf("loop start\r\n");

	__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE);
	HAL_UART_Receive_DMA(&huart2, (uint8_t *)uartRxBuffer, 255);
	while (1) {
		if (UartIRQFlag) {
			UartIRQFlag = 0;
			uint8_t data_length = BUFFER_SIZE - __HAL_DMA_GET_COUNTER(&hdma_usart2_rx); //计算接收到的数据长度

			app_dprintf("Receive Data(length = %d): ", data_length);
			//HAL_UART_Transmit(&huart2, uartRxBuffer, data_length, 0x200); //测试函数：将接收到的数据打印出去
			app_dprintf(uartRxBuffer);
			app_dprintf("\r\n");

			// excute shell
			vtrecv_execute(&(ntshell.vtrecv), uartRxBuffer, data_length);

			//清零接收缓冲区
			memset(uartRxBuffer, 0, data_length); 
			data_length = 0;
			//重启开始DMA传输 每次255字节数据	
			HAL_UART_Receive_DMA(&huart2, (uint8_t*)uartRxBuffer, 255);                    
		}
		HAL_Delay(1);
	}
}

void app_dprintf(const char *format, ...)
{
	if (app_debug != 0) {
		char pszBuff[256];
		char dbgfmt[64];

		va_list args;
		va_start(args, format);

		strcpy(dbgfmt, "[DEBUG]\t");
		strcat(dbgfmt, format);

		vsprintf(pszBuff, dbgfmt, args);
		printf(pszBuff);
		va_end(args);
	}
}
